// subPages/health/shopCart/shopCart.js
const app = getApp();
var util =  require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEditor: false,
    isAllCheck: false,
    total: 0,//合计
    buyNum: 0,//购买数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
      //获取购物车数据
      that.getData()
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
          //获取购物车数据
          that.getData()
        }
      }
    }
  },

  //获取购物车数据
  getData:function(){
    util.getAjax(app.globalData.apiUrl +'/get_community_health_shop_product_buycar',this.getCartData,{user_id: this.data.userId})
  },

  //获取购物车数据
  getCartData(res){
    console.log(res)
    var that = this
    var total = 0
    var buyNum = 0
    var freight = 0//运费
    if(res.data.length != 0){
      for(let i in res.data){
        for(let j in res.data[i].items){
          res.data[i].items[j].isCheck = false
          res.data[i].items[j].isFailure = res.data[i].items[j].status == 0?false:true
          res.data[i].items[j].isSoldOut = res.data[i].items[j].product_content.pay_no != 0?false:true
        }
      }
      if(that.data.shopCartList){
        let list = that.data.shopCartList
        for(let i in list){
          for(let j in list[i].items){
            if(list[i].items[j].isCheck && list[i].items[j].status == 0 && list[i].items[j].product_content.pay_no != 0){
              for(let z in res.data){
                for(let h in res.data[z].items){
                  if(list[i].items[j].id == res.data[z].items[h].id){
                    res.data[z].items[h].isCheck = true
                    total += (Number(res.data[z].items[h].price) * Number(res.data[z].items[h].num)) + Number(res.data[z].items[h].product_content.yunfei?res.data[z].items[h].product_content.yunfei:0)
                    freight += Number(res.data[z].items[h].product_content.yunfei?res.data[z].items[h].product_content.yunfei:0)
                    buyNum ++ 
                  }
                }
                
              }
            }
          }
        }
      }
      var isAllCheck = true
      for(let z in res.data){
        for(let h in res.data[z].items){
          if(!res.data[z].items[h].isCheck && res.data[z].items[h].status == 0){
            isAllCheck = false
            break;
          }
        }
      }
      that.setData({
        isHaveData: true,
        isEditorAre: true,
        shopCartList: res.data,
        total: total,
        buyNum: buyNum,
        freight: freight,
        isAllCheck: isAllCheck
      })
    }else{
      that.setData({
        isHaveData: false,
        isEditorAre: false,
        total: total,
        freight: freight,
        buyNum: buyNum,
      })
    }
  },

  //选择购物车
  selectCart:function(e){
    // console.log(e)
    var that = this
    var id = e.currentTarget.dataset.id
    var list = that.data.shopCartList;
    var total = that.data.total
    var freight = that.data.freight
    var buyNum = that.data.buyNum
    for(let i in list){
      for(let j in list[i].items){
        if(list[i].items[j].id == id && list[i].items[j].status == 0 && list[i].items[j].product_content.pay_no != 0){
          if(list[i].items[j].isCheck){
            //已选择
            total -= (Number(list[i].items[j].price) * Number(list[i].items[j].num)) + Number(list[i].items[j].product_content.yunfei?list[i].items[j].product_content.yunfei:0)
            freight -= Number(list[i].items[j].product_content.yunfei?list[i].items[j].product_content.yunfei:0)
            buyNum --
            if(that.data.isAllCheck){
              that.setData({
                isAllCheck: false
              })
            }
          }else{
            //未选择
            total += (Number(list[i].items[j].price) * Number(list[i].items[j].num))+Number(list[i].items[j].product_content.yunfei?list[i].items[j].product_content.yunfei:0)
            freight += Number(list[i].items[j].product_content.yunfei?list[i].items[j].product_content.yunfei:0)
            buyNum ++
          }
          list[i].items[j].isCheck= !list[i].items[j].isCheck
        }
      }
    }
    var isAllCheck = true
    for(let i in list){
      for(let j in list[i].items){
        if(!list[i].items[j].isCheck && list[i].items[j].status == 0 && list[i].items[j].product_content.pay_no != 0){
          isAllCheck = false
          break;
        }
      }
      
    }
    that.setData({
      shopCartList: list,
      total: total,
      freight: freight,
      buyNum: buyNum,
      isAllCheck: isAllCheck
    })
  },

  //增减数量
  modifyNumber:function(e){
    var that = this
    var id = e.currentTarget.dataset.id    
    var type = e.currentTarget.dataset.type
    var list = that.data.shopCartList
    for(let i in list){
      for(let j in list[i].items){
        if(list[i].items[j].id == id && list[i].items[j].status == 0 && list[i].items[j].product_content.pay_no != 0){
          switch (type) {
            case 'add':
              list[i].items[j].num ++
              break;
            case 'subtract':
              list[i].items[j].num --
              break;
          }
          util.getAjax(app.globalData.apiUrl +'/operation_community_health_shop_product_buycar',function(res){
            // console.log(res)
            if(res.data==1){
              //获取购物车数据
              that.getData()
            }
          },{type: 2,id: list[i].items[j].id,num: list[i].items[j].num,price: list[i].items[j].price,})
        }
      }
    }
  },

  //编辑按钮
  editorBtn:function(){
    this.setData({
      isEditor: true
    })
  },

  //完成按钮
  completeBtn:function(){
    this.setData({
      isEditor: false
    })
  },

  //全选
  allCheck:function(){
    var that = this
    var list = that.data.shopCartList
    var total = that.data.total
    var freight = that.data.freight
    var buyNum = that.data.buyNum
    var isAllCheck = that.data.isAllCheck
    for(var i in list){
      for(let j in list[i].items){
        if(list[i].items[j].status == 0 && list[i].items[j].product_content.pay_no != 0){
          if(that.data.isAllCheck)
          {
            //已经全选
            list[i].items[j].isCheck = false
            total = 0
            buyNum  = 0
            freight = 0
            isAllCheck = false
          }else
          {
            //没有全选
            list[i].items[j].isCheck = true
            total += (Number(list[i].items[j].price) * Number(list[i].items[j].num)) + Number(list[i].items[j].product_content.yunfei?list[i].items[j].product_content.yunfei:0)
            freight += Number(list[i].items[j].product_content.yunfei?list[i].items[j].product_content.yunfei:0)
            buyNum ++
            isAllCheck = true
          }
        }
      }
    }
    that.setData({
      shopCartList: list,
      total: total,
      freight: freight,
      buyNum: buyNum,
      isAllCheck: isAllCheck
    })
  },

  //删除商品
  deleteBtn:function(e){
    var that = this
    var idList = []
    idList.push(e.currentTarget.dataset.id)
    if(idList.length != 0){
      util.showModelAll('提示','您是否确定删除该商品？',function(){
        util.getAjax(app.globalData.apiUrl +'/operation_community_health_shop_product_buycar',function(res){
          // console.log(res);
          if(res.data == 1){
              util.showToast('已删除','none',1000);
              //获取购物车数据
              that.getData()
          }
        },{type: 3,id: idList})
      })
    }
  },

  //删除选择的商品
  deleteSelectBtn:function(){
    var that = this
    var list = that.data.shopCartList
    var idList = []
    for(var i in list){
      for(let j in list[i].items){
        if(list[i].items[j].isCheck){
          idList.push(list[i].items[j].id)        
        }
      }
    }
    if(idList.length != 0){
      util.showModelAll('删除商品','您是否确定删除所选商品？',function(){
        util.getAjax(app.globalData.apiUrl +'/operation_community_health_shop_product_buycar',function(res){
          // console.log(res);
          if(res.data == 1){
              util.showToast('已删除','none',1000);
              //获取购物车数据
              that.getData()
          }
        },{type: 3,id: idList})
      })
    }else{
      util.showModal('提示','您还没有选择商品')
    }
  },

  //清空购物车
  emptyCartBtn:function(){
    var that = this
    var list = that.data.shopCartList
    var idList = []
    for(var i in list){
      for(let j in list[i].items){
        idList.push(list[i].items[j].id)    
      }
    }
    if(idList.length != 0){
      util.showModelAll('清空购物车','您是否确定删除购物车？',function(){
        util.getAjax(app.globalData.apiUrl +'/operation_community_health_shop_product_buycar',function(res){
          // console.log(res);
          if(res.data == 1){
              util.showToast('已清空','none',1000);
              //获取购物车数据
              that.getData()
              that.setData({
                isEditor: false
              })
          }
        },{type: 3,id: idList})
      })
    }else{
      util.showModal('提示','当前购物车暂无商品')
    }
  },

  //清空失效产品
  emptyFailureBtn:function(){
    var that = this
    var list = that.data.shopCartList
    var idList = []
    for(var i in list){
      for(let j in list[i].items){
        if(list[i].items[j].status == 1 || list[i].items[j].product_content.pay_no == 0){
          idList.push(list[i].items[j].id)        
        }
      }
    }
    if(idList.length != 0){
      util.showModelAll('删除失效商品','您是否确定删除失效商品？',function(){
        util.getAjax(app.globalData.apiUrl +'/operation_community_health_shop_product_buycar',function(res){
          // console.log(res);
          if(res.data == 1){
              util.showToast('已删除','none',1000);
              //获取购物车数据
              that.getData()
          }
        },{type: 3,id: idList})
      })
    }else{
      util.showModal('提示','暂无失效商品')
    }
  },

  //点击食品
  clickGoods:function(e){
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/subPages/health/healthShopDetails/healthShopDetails?id=' + id,
    })
  },

  //购买
  buyBtn:function(){
    var that = this
    if(that.data.buyNum == 0){
      util.showModal('提示','请选择商品')
      return
    }
    var list = that.data.shopCartList
    var idList = []
    for(var i in list){
      for(let j in list[i].items){
        if(list[i].items[j].isCheck){
          idList.push(list[i].items[j].id)        
        }
      }
    }
    wx.navigateTo({
      url: '/subPages/health/submitOrders/submitOrders?list=' + JSON.stringify(idList) + '&total=' + this.data.total + '&type=' + 2
    })
  },

  //回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 600) {
      this.setData({
        isTop: true
      });
    } else {
      this.setData({
        isTop: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      isEditor: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      isEditor: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})